package com.example.dbdesign.filter;

import com.example.dbdesign.pojo.vo.LoginUser;
import com.example.dbdesign.utils.JwtUtil;
import com.example.dbdesign.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        System.out.println(token + " 这是token");
        System.out.println(!StringUtils.hasText(token));
        if (!StringUtils.hasText(token)){
            // 放行
            filterChain.doFilter(request, response);
            return;
        }
        String userid;
        try{
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
            System.out.println(claims);
            System.out.println(userid + ' ' + "id");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        // redis拿信息

        LoginUser loginuser = redisCache.getCacheObject(userid);
        System.out.println(loginuser);
        if (loginuser == null){
            throw new RuntimeException("用户未登录");
        }
        //存入SecurityContextHolder
        // 获取信息封装到Authentication
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(loginuser, null , loginuser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }
}
